// components/search/index.js
import {KeywordModel} from "../../modules/keyword.js";
import {BookModel} from "../../modules/book.js";
 let keywordModel=new KeywordModel();
 let bookModel=new BookModel();
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    more: {
      type: Number,
      observer:"_load_more"
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    q:"",
    historyWords:[],
    hotWords:[],
    dataArray:[],
    searching:false, //搜索结果
    loading:false,     //是否再请求数据
    Null: false //加载数据是否为空
  },
  attached(){
    this.setData({
      historyWords: keywordModel.getHistory()
    });
    keywordModel.getHot().then((res)=>{
        this.setData({
          hotWords:res.hot
        })
      })
  },
  /**
   * 组件的方法列表
   */
  methods: {
    _load_more() {
      if(!this.data.q){
          return;
      }
      if(this.data.loading) //如果为真的话 就是再请求不会执行下面的
      {
        return;
      }
      console.log(1);
       //获取更多是通过个数来获取的
      if(!this.data.Null){
        this.data.loading = true; //锁住
        const length = this.data.dataArray.length; 
        bookModel.search(length, this.data.q).then(res => {
          if(res.books.length==0)
          {
            this.data.Null=true;
          }
          const tempArray = this.data.dataArray.concat(res.books); //合并数组
          this.setData({
            dataArray: tempArray
          });
          this.data.loading = false; //解开
        })
      }
    
    },
    onCancel:function(){
      this.triggerEvent("cancle");
    },
    onDelete:function(){
      this.setData({
        searching:false,
        q:""
      })
    },
    onConfirm:function(ev){
      const word = ev.detail.value || ev.detail.text;
      this.setData({
        searching:true,
        q:word
      })
      bookModel.search(0,word).then(res=>{
        this.setData({
          dataArray:res.books
        });
        keywordModel.addToHistory(word);
      })  
    }
  }
})
